package cn.nkpro.elcube.docengine.cloud;

import cn.nkpro.elcube.data.redis.RedisSupport;
import cn.nkpro.elcube.docengine.NkDocEngine;
import cn.nkpro.elcube.docengine.model.DocHV;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.Assert;

/**
 * 基于redis的MDM 远程锁实现
 */
public class NkCloudDocEngineLockImpl implements NkCloudDocEngineLock {

    @Autowired
    private RedisSupport<String> redisSupport;

    @Qualifier("NkDocEngineFrontService")
    @Autowired
    private NkDocEngine docEngine;

    @Override
    public boolean obtainTemporaryLock(String docId, String validateIdentification ,String password) {
        DocHV detail = docEngine.detail(docId);
        if(detail!=null){
            Assert.isTrue(StringUtils.equals(detail.getIdentification(),validateIdentification),"单据与主数据服务未同步");
        }
        return redisSupport.lock("CLOUD:"+docId, password,60 * 10);
    }

    @Override
    public boolean obtainPermanentLock(String docId, String lock) {

        String lockKey = "LOCK:CLOUD:"+docId;
        String tempValue = redisSupport.get(lockKey);
        if(lock!=null && StringUtils.equals(tempValue,lock)){
            redisSupport.expire(lockKey,60*60*24*365);
            return true;
        }
        return false;
    }

    @Override
    public void releaseLock(String docId, String lock) {
        redisSupport.unlock("CLOUD:"+docId,lock);
    }
}
